<?php
###
#  Baing PHP 框架 1.0.0
#  http://baing.co/
#
#  Copyright: 白晓阳
#  License: CC BY-NC-SA 4.0
#  https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh
###

namespace bai\action;

use bai\resource\application\Database, bai\resource\document\DataTable;


/**
 * Runtime
 * [
 *     'resource' => 'resource',
 *     'method' => 'GET',
 *     'query' => ['field1' => 'value1', 'field2' => 'value2', ...]
 *     'data' => ['field1' => 'value1', 'field2' => 'value2', ...]
 *     'fields' => ['field1', 'field2', ...]
 *     'links => ['link1', 'link2' => ['query' => [...], 'links' => [...]], ...]
 *     'quality' => ['order' => ['field1', ...], 'group' => ['field1' => 'ASC', ...], 'page' => 2]
 * ]
 * [
 *     'query' => 'query',
 *     'params' => ['field1' => 'value1', 'field2' => 'value2', ...]
 * ]
 */
class DataAccess extends \bai\Action
{
    public function run()
    {
        if (!$this->find('sql')) {
            $dataQuery = $this->find('DataQuery') ?? 'DataQuery';
            $query = $this->runAction($dataQuery, $this->runtime);
            $this->runtime = array_replace($this->runtime, $query);
        }

        $database = Database::setup();
        $result = $database->run($this->runtime);

        if ($result['status'] && ($links = $this->find('links')) && !empty($result['result']['records'])) {
            $resource = $this->find('resource') ?? self::$process->resource;
            $table = DataTable::setup(['path' => $resource]);
            $table->run();
            $filtered = $table->filterLinks((array) $links);
            foreach ($filtered as $name => $link) {
                $link['id'] = $name;
                $link['resource'] = $link['name'] ?? $name;
                $link['method'] = self::GET;
                $this->link($result['result'], $link);
            }
        }

        return $this->next($result['result'], $result['status'] ? self::SUCCEEDED : self::FAILED);
    }

    protected function link(array &$data, array $link)
    {
        $field = $link['linkFrom'];
        if (!array_key_exists($field, $data['records'][0])) return;

        $params = [];
        foreach ($data['records'] as $record) {
            if (!isset($record[$field])) continue;
            $params[$record[$field]] = $record[$field];
        }
        if (!$params) return;
        $link['query'][$link['linkTo'] ?? 'id'] = array_values($params);

        $result = $this->runAction(static::class, $link);
        $data['links'][$link['id']] = $result;
    }
}
